package com.self.cloudmall.oms.controller;

import com.self.cloudmall.common.utils.R;
import com.self.cloudmall.oms.service.OrderService;
import com.self.cloudmall.oms.vo.OrderConfirmVo;
import com.self.cloudmall.oms.vo.SubmitOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Slf4j
@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;


    /**
     * 跳转订单确认页
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model){
        OrderConfirmVo orderConfirm =  orderService.getOrderConfirm();
        model.addAttribute("confirm",orderConfirm);
        return "confirm";
    }

    /**
     * 创建订单
     * @param submitOrder
     * @param model
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(SubmitOrderVo submitOrder, Model model, RedirectAttributes attributes){
        try {
            R r = orderService.submitOrder(submitOrder);
            //成功进入支付页
            if (r.isSuccess()){
                model.addAttribute("order",r.getData());
                return "payment";
            }
            attributes.addFlashAttribute("msg",r.get("msg"));
        } catch (Exception e) {
           log.error("提交订单异常：{}",e);
            attributes.addFlashAttribute("msg",e.getMessage());
        }
        //失败重新进入订单确认页
        return "redirect:http://order.cloudmall.com/toTrade";
    }

    /**
     * @Title: 支付
     * @Description:
     * @Param [orderSn, model]
     * @Return java.lang.String
     * @Author M10003729
     * @Throws
     * @Date 2021/1/29 17:57
     */
    @GetMapping(value = "/pay",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String pay(String orderSn,Model model){
        R r = orderService.pay(orderSn);
        if (!r.isSuccess()){
            model.addAttribute("payMsg",r.get("msg"));
            model.addAttribute("order",r.getData());
            return "payment";
        }
        return (String) r.getData();
    }
}
